package com.bawei.rk_01.xq

import android.R.attr
import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.PopupMenu
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.utils.mvvm.BaseAcitivity
import com.bawei.rk_01.Adapter.GlideUtils
import com.bawei.rk_01.Adapter.GoodsAdapter
import com.bawei.rk_01.R
import com.bawei.rk_01.databinding.ActivityXqBinding
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.editorpage.ShareActivity
import com.umeng.socialize.media.UMImage
import com.youth.banner.loader.ImageLoader


@Route(path = "/app/XqActivity")

class XqActivity : BaseAcitivity<ActivityXqBinding,XqViewModel>() {

    @Autowired(name = "index")
    @JvmField
    var index :Int = 1

    lateinit var addcarId : String
    lateinit var imageUrl : String
    var codeString = ""  //生成二维码的内容

    lateinit var couponsAdapter2: CouponsAdapter2
    lateinit var goodsAdapter: GoodsAdapter

    val list = ArrayList<String>()

    override fun getViewModel(): Class<XqViewModel> {
        return XqViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.activity_xq
    }

    override fun initView() {

        //动态获取权限
        requestPermissions(arrayOf("android.permission.VIBRATE",
            "android.permission.RECORD_AUDIO" ,
            "android.permission.CAMERA",
            "android.permission.ACCESS_NETWORK_STATE",
            "android.permission.WRITE_EXTERNAL_STORAGE" ,
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.GET_TASKS" ,
            "android.permission.ACCESS_WIFI_STATE" ,
            "android.permission.CHANGE_WIFI_STATE" ,
            "android.permission.WAKE_LOCK",
            "android.permission.MODIFY_AUDIO_SETTINGS",
            "android.permission.READ_PHONE_STATE",
            "android.permission.RECEIVE_BOOT_COMPLETED",
            "android.permission.FOREGROUND_SERVICE",
            "android.permission.ACCESS_COARSE_LOCATION"),200)

        //实例化
        ARouter.getInstance().inject(this)

        viewModel.goodsxu(index,"nomal")

        //点击返回按钮
        binding.left.setOnClickListener {
            finish()
        }
        //点击更多，弹出菜单，点击内容跳到对应界面
        binding.more.setOnClickListener {
            val popupMenu = PopupMenu(this,binding.more)
            popupMenu.inflate(R.menu.xy_menu)
            popupMenu.setOnMenuItemClickListener {
                when(it.itemId){
                    R.id.home->{
                        ARouter.getInstance().build("/app/MainActivity").navigation()
                    }
                    R.id.search->{
                        ARouter.getInstance().build("/app/SearchActivity").navigation()
                    }
                    R.id.car->{
                        ARouter.getInstance().build("/app/MainActivity").withInt("ym",2).navigation()
                    }
                    R.id.share->{
                        ToastUtils.showLong("收藏")
                    }
                    R.id.person->{
                        ARouter.getInstance().build("/app/MainActivity").withInt("ym",3).navigation()
                    }
                }
                return@setOnMenuItemClickListener true
            }
            popupMenu.show()
        }

        //点击购物车图标
        binding.car.setOnClickListener {
            ARouter.getInstance().build("/app/MainActivity").withInt("ym",2).navigation()
        }

        //优惠卷
        couponsAdapter2 = CouponsAdapter2()
        binding.yhj.layoutManager = LinearLayoutManager(this)
        binding.yhj.adapter = couponsAdapter2
        viewModel.getcoupons(1,1,1)

        //优品推进
        goodsAdapter = GoodsAdapter()
        binding.xqTuijian.layoutManager = GridLayoutManager(this,3,GridLayoutManager.HORIZONTAL,false)
        binding.xqTuijian.adapter = goodsAdapter
        viewModel.goodsYp()


        //点击加入购物车
        binding.addcar.setOnClickListener {
            viewModel.addcar(1,addcarId,index)
        }

        //点击分享 弹出对话框生成二维码
        binding.fenxiang.setOnClickListener {
            val ewm = LayoutInflater.from(this).inflate(R.layout.item_ewm,null)

            //生成二维码
            val bitmap = BarcodeEncoder().encodeBitmap(codeString,BarcodeFormat.QR_CODE,200,200)
            ewm.findViewById<ImageView>(R.id.iv).setImageBitmap(bitmap)

            val aler = AlertDialog.Builder(this)
                .setView(ewm)
                .create()
            ewm.findViewById<Button>(R.id.no).setOnClickListener {
                aler.dismiss()
            }
            ewm.findViewById<Button>(R.id.yes).setOnClickListener {
                aler.dismiss()
                val image: UMImage = UMImage(this, bitmap) //bitmap文件
                ShareAction(this).withText("hello").withMedia(image)
                    .setDisplayList(SHARE_MEDIA.QQ)
                    .setCallback(object : UMShareListener {
                        override fun onStart(p0: SHARE_MEDIA?) {

                        }

                        override fun onResult(p0: SHARE_MEDIA?) {

                        }

                        override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                            ToastUtils.showLong(p1?.message)
                        }

                        override fun onCancel(p0: SHARE_MEDIA?) {

                        }
                    })
                    .open()
            }
            //点击弹框外部，可以关闭弹框
            aler.setCanceledOnTouchOutside(true)
            aler.show()

        }

    }

    override fun initData() {

        viewModel.xqsuccess.observe(this){
            if (it.code == 200){

                addcarId = it.data.productValue.values.toList().get(0).id.toString()

                //轮播图
                list.add(it.data.productInfo.image)
                list.add(it.data.productInfo.image)
                list.add(it.data.productInfo.image)
                imageUrl = it.data.productInfo.image
                binding.banner.setImages(list)
                binding.banner.setImageLoader(object : ImageLoader() {
                    override fun displayImage(
                        context: Context?,
                        path: Any?,
                        imageView: ImageView?
                    ) {
                        if (context != null && imageView!=null) {
                            Glide.with(context).load(path).into(imageView)
                        }
                    }
                }).start()

                //双向数据绑定
                binding.info = it.data.productInfo
                //默认选中的规格
                binding.sku.text = "已选择：${it.data.productValue.keys.toList().get(0)} "

                if (it.data.userCollect){
                    binding.shoucang.setCompoundDrawablesWithIntrinsicBounds(0,
                        R.drawable.baseline_favorite_24, 0, 0) // 切换为未收藏图标
                }else{
                    binding.shoucang.setCompoundDrawablesWithIntrinsicBounds(0,
                        R.drawable.baseline_favorite_border_24, 0, 0) // 切换为未收藏图标
                }

                //点击收藏,再次点击取消收藏
                binding.shoucang.setOnClickListener { it2->
                    if (it.data.userCollect){
                        //为真表示已经收藏，执行取消收藏
                        viewModel.noshare(index)
                    }else{
                        viewModel.share("store",index)
                    }
                }

                //二维码进行赋值
                codeString = "${it.data.productInfo.storeName}"

            }
        }
        viewModel.xqfail.observe(this){
            ToastUtils.showLong(it)
        }

        viewModel.couponssuccess.observe(this){
            if (it.code == 200){
                couponsAdapter2.data.clear()
                couponsAdapter2.data.addAll(it.data)
                couponsAdapter2.notifyDataSetChanged()
            }
        }

        viewModel.ypsuccess.observe(this){
            if (it.code == 200){
                goodsAdapter.data.clear()
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
            }
        }

        //收藏和取消收藏
        viewModel.sharesuccess.observe(this){
            if (it.code == 200){
                //更换文本中的图片
                binding.shoucang.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.baseline_favorite_24, 0, 0) // 切换为未收藏图标
                ToastUtils.showLong("收藏成功")
                viewModel.goodsxu(index,"nomal")
            }
        }
        viewModel.sharefail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.nosharesuccess.observe(this){
            if (it.code == 200){
                binding.shoucang.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.baseline_favorite_border_24, 0, 0) // 切换为未收藏图标
                ToastUtils.showLong("取消收藏")
                viewModel.goodsxu(index,"nomal")
            }
        }
        viewModel.nosharefail.observe(this){
            ToastUtils.showLong(it)
        }

        //加入购物车
        viewModel.addcarsuccess.observe(this){
            if (it.code == 200){
                ToastUtils.showLong("加入购物车成功")

                //加入购物车动画
                val imageView = ImageView(this)
                imageView.layoutParams = ViewGroup.LayoutParams(200,200)
                GlideUtils.loadImage(this,imageUrl,imageView)
                binding.main.addView(imageView)
                //设置动画
                val width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()
                val animator =
                    ObjectAnimator.ofFloat(imageView, "translationX", 0f, width, width * 2 / 3).setDuration(1000)
                val animator1 = ObjectAnimator.ofFloat(imageView, "translationY", 0f, height).setDuration(1500)
                val animator2 = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 3600f).setDuration(2000)
                val set = AnimatorSet()
                set.play(animator2).before(animator1).before(animator)
                set.addListener(object : AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {

                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.main.removeView(imageView)
                    }

                    override fun onAnimationCancel(animation: Animator) {

                    }

                    override fun onAnimationRepeat(animation: Animator) {

                    }
                })
                set.start()

            }
        }
        viewModel.addcarfail.observe(this){
            ToastUtils.showLong(it)
        }

    }

}